﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace IDEAMS.common.validation
{
    public enum InputType
    {
        String = 0,
        Integer,
        Double
    }

    public class NumberRule : ValidationRule
    {
        public NumberRule()
        {
            isNullable = true;
            inputType = InputType.Double;
        }
        public string errString { get; set; }

        public double? minValue { get; set; }

        public double? maxValue { get; set; }

        public InputType inputType { get; set; }
        public string regex { get; set; }

        public bool isNullable { get; set; }
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            bool rn = true;

            try
            {
                //如果值为空
                if (string.IsNullOrEmpty((string)value))
                {
                    //不允许为空
                    if (!isNullable)
                    {
                        return new ValidationResult(false, $"不能为空");
                    }
                    else //允许为空
                    {
                        return ValidationResult.ValidResult;
                    }
                }

                double dValue = double.NaN;

                switch (inputType)
                {
                    case InputType.Integer:
                        dValue = int.Parse((string)value);
                        break;

                    case InputType.Double:
                        dValue = double.Parse((string)value);
                        break;

                    default:
                        dValue = double.Parse((string)value);
                        break;
                }

                //if(dValue.Equals(double.NaN))
                //{
                //    return new ValidationResult(false, $"输入字符不合法");
                //}

                if ((minValue != null && dValue < minValue)
                || (maxValue != null && dValue > maxValue))
                {
                    return new ValidationResult(false, errString);
                }

                if (!string.IsNullOrEmpty(regex))
                {
                    rn = Regex.IsMatch((string)value, regex);
                    if (rn == false)
                    {
                        return new ValidationResult(false, errString);
                    }
                }

            }
            catch (Exception)
            {
                return new ValidationResult(false, errString);
            }

            if (rn == false)
            {
                return new ValidationResult(false, errString);
            }

            return ValidationResult.ValidResult;
        }
    }
}
